package com.cqeec.demo.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.cqeec.demo.bean.AdminUser;
import com.cqeec.demo.config.WebConfig;

/**
 * 后台登录权限过滤器
 * 
 * @Title: AdminAccessPermissionFilter
 * @Descripton: 
 *    1、后台所有操作都需要这个过滤器来进行过滤操作，如果没有登录就跳到后台管理登录界面
 *    2、登录成功后，根据请求判断是否具有相应权限
 */
public class AdminAccessPermissionFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String urlpath = req.getServletPath();
		HttpSession session = req.getSession();
		AdminUser adminUser = (AdminUser) session.getAttribute("system_admin_login_info");
		//排除不需要进行权限判断的请求
		if (WebConfig.No_Interceptor_URL.indexOf(urlpath)!=-1) {
			chain.doFilter(request, response);
		}
		// 先判断是否登录
		else if (adminUser == null) {
			res.setContentType("text/html;charset=utf-8");
			PrintWriter out = res.getWriter();
			out.println("<script language='javascript' type='text/javascript'>");
			out.println("alert('请先登录');");
			out.println("window.top.location.href='" + req.getContextPath() + "/login.jsp'");
			out.println("</script>");
			out.flush();
			out.close();
		}
		// 用户权限判断
		else {
			String user_auth = (String) session.getAttribute("user_role_auth");
			if (user_auth.indexOf(urlpath) == -1) {
				res.setContentType("text/html;charset=utf-8");
				PrintWriter out = res.getWriter();
				out.println("{\"message\":\"您无权访问\",\"status\":false}");
				out.flush();
				out.close();
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {

	}

}
